import { useEffect, useRef, useState } from "react";
import ProForm, {
  ProFormText,
  ProFormRadio,
  ProFormDependency,
  ProFormSelect,
  ProFormTextArea,
  ProFormTreeSelect,
  ProFormList,
} from "@ant-design/pro-form";
import ProCard from "@ant-design/pro-card";
import { message } from "antd";
import { LeftOutlined } from "@ant-design/icons";

import { add, update, fetchInfo } from "@/api/freeTemplate";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import { useLocation, history } from "umi";
import CarryModeTables from "@/components/CarryModeTables";
import FreeTables from "@/components/FreeTables";

import { valuationModelOptions, freeOrNoOptions } from "@/const";

export default () => {
  const location = useLocation();
  const { id } = location.query;
  const title = id ? "编辑运费模板" : "新增运费模板";
  const formRef = useRef();
  const [info, setInfo] = useState({});

  const getInfo = async () => {
    const res = await fetchInfo({ id: id });
    setInfo(res.data);
    if (res.data) {
      const postData = {
        ...res.data,
        carryModeS: res.data?.carryModeS.map((item) => {
          return {
            ...item,
            id: item.carryModeId,
            region:
              item.region === "ALL"
                ? "ALL"
                : item.region.split("|").map((sub) => {
                    return sub.split("-");
                  }),
          };
        }),
        delayedTerms: res.data?.delayedTerms.map((item) => {
          return {
            ...item,
            id: Math.random().toString(),
            region: item.region.split("|").map((sub) => {
              return sub.split("-");
            }),
          };
        }),
      };
      console.log("postData===", postData);
      formRef.current.setFieldsValue(postData);
    }
  };

  const defaultData = {
    carryModeS: [
      {
        id: Date.now(),
        firstBulk: 1,
        firstPiece: 1,
        firstPrice: 1,
        firstWeight: 1,
        region: "ALL",
        secondBulk: 1,
        secondPiece: 1,
        secondPrice: 1,
        secondWeight: 1,
      },
    ],
    delayedTerms: [
      {
        id: Date.now(),
        bulkNo: 1,
        pieceNo: 1,
        price: 1,
        region: "11-1101-110101",
        weightNo: 1,
      },
    ],
    freeOrNot: 0,
    freeOrNot: 1,
    tempName: "运费1",
    valuationModel: 0,
  };

  useEffect(() => {
    // formRef.current.setFieldsValue(defaultData);
    if (id) {
      getInfo();
    }
  }, []);

  const handleAddOrUpdate = async (fields) => {
    let postData = {
      ...fields,
      id,
      delayedTerms: fields.delayedTerms?.map((item) => {
        delete item.id;
        return {
          ...item,
          region: item.region
            .map((sub) => {
              return sub.join("-");
            })
            .join("|"),
        };
      }),
      carryModeS: fields.carryModeS?.map((item) => {
        delete item.id;
        return {
          ...item,
          region:
            item.region === "ALL"
              ? "ALL"
              : item.region
                  .map((sub) => {
                    return sub.join("-");
                  })
                  .join("|"),
        };
      }),
    };
    let func = add;
    if (id) {
      func = update;
      postData = {
        ...info,
        ...postData,
      };
    }
    const res = await func(postData);
    if (res.code == 200) {
      message.success(title + "成功");
      history.goBack();
    }
  };

  return (
    <PageContainer
      header={{
        title: (
          <div className="pointer" onClick={() => history.goBack()}>
            <LeftOutlined style={{ marginRight: 10 }} />
            {title}
          </div>
        ),
        breadcrumb: {},
      }}
    >
      <ProForm
        layout="horizontal"
        formRef={formRef}
        onFinish={async (values) => {
          return handleAddOrUpdate(values);
        }}
        submitter={{
          render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
        }}
        labelCol={{
          span: 4,
        }}
        initialValues={{
          valuationModel: 0,
          freeOrNot: 0,
          carryModeS: [
            {
              id: Date.now(),
              region: "ALL",
              firstPiece: 1,
              firstPrice: 0,
              secondPiece: 1,
              secondPrice: 0,

              firstWeight: 1,
              secondWeight: 1,

              firstBulk: 1,
              secondBulk: 1,
            },
          ],
        }}
      >
        <ProCard title="基础信息" bordered>
          <ProFormText
            width="lg"
            label="模板名称"
            name="tempName"
            rules={[
              { required: true, message: "请输入模板名称" },
              {
                max: 50,
                message: "最长为50位",
              },
            ]}
          />

          <ProFormRadio.Group
            label="计费方式"
            name="valuationModel"
            options={valuationModelOptions}
            rules={[{ required: true, message: "请选择计费方式" }]}
          />

          <ProFormDependency name={["valuationModel"]}>
            {({ valuationModel }) => {
              return (
                <ProForm.Item
                  name="carryModeS"
                  label="配送区域及运费"
                  rules={[{ required: true, message: "请设置配送区域及运费" }]}
                >
                  <CarryModeTables
                    valuationModel={valuationModel}
                    name="carryModeS"
                  />
                </ProForm.Item>
              );
            }}
          </ProFormDependency>

          <ProFormRadio.Group
            label="指定包邮"
            name="freeOrNot"
            options={freeOrNoOptions}
            rules={[{ required: true, message: "请选择" }]}
          />

          <ProFormDependency name={["valuationModel", "freeOrNot"]}>
            {({ valuationModel, freeOrNot }) => {
              return (
                freeOrNot === 1 && (
                  <ProForm.Item
                    name="delayedTerms"
                    label="包邮设置"
                    rules={[{ required: true, message: "请设置包邮" }]}
                  >
                    <FreeTables
                      valuationModel={valuationModel}
                      name="delayedTerms"
                    />
                  </ProForm.Item>
                )
              );
            }}
          </ProFormDependency>
        </ProCard>
      </ProForm>
    </PageContainer>
  );
};
